package com.brian.mqproducer.consumer;

import com.alibaba.fastjson.JSONObject;
import com.brian.mqproducer.entity.OrderEntity;
import com.brian.mqproducer.mapper.OrderMapper;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Map;

/**
 * @program: architect  补单服务
 * @author: Brian Huang
 * @create: 2019-07-17 19
 **/
@Component
public class CreateOrderConsumer {

    @Resource
    private OrderMapper orderMapper;

    @RabbitListener(queues = "order_create_queue")
    public void process(Message message, @Headers Map<String, Object> headers, Channel channel) throws IOException {
        String messageId = message.getMessageProperties().getMessageId();
        String msg = new String(message.getBody(), "UTF-8");
        System.out.println("订单平台补单服务接受口到的消息ID: " + messageId);
        System.out.println("订单平台补单服务接受口到的消息: " + msg);
        JSONObject jsonObject = (JSONObject) JSONObject.parse(msg);
        String orderId = (String) jsonObject.get("orderId");
        if(StringUtils.isEmpty(orderId)){
            //手动签收消息，通知mq服务器端删除该消息
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            return;
        }
        OrderEntity orderEntity = orderMapper.findByOrderId(orderId);
        if(orderEntity != null){
            //该订单已经创建，通知服务器端删除该消息
            System.out.println("该订单已经创建！！");
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
            return;
        }
        System.out.println("开始执行补单，补单的orderId: " + orderId);
        // 使用补偿机制
        OrderEntity order = new OrderEntity();
        order.setName("腾讯云redis钛合金");
        order.setOrderCreatetime(new Date());
        order.setOrderMoney(3000d);
        // 状态为 未支付
        order.setOrderState(0);
        Long commodityId = 1234567654345l;
        // 商品id
        order.setCommodityId(commodityId);
        order.setOrderId(orderId);

        // 1.先下单，创建订单 (往订单数据库中插入一条数据)
        OrderEntity orderResult = orderMapper.save(order);
        System.out.println("orderResult:" + orderResult);
        if (orderResult != null) {
            // 手动签收消息,通知mq服务器端删除该消息
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            return;
        }
        // 重试进行补偿 多次失败 使用日志记录 采用定时job检查或者 人工补偿

    }
}
